package com.zhang.second.day02;

import com.zhang.second.utils.IntegerSource;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @title: reduce算子求平均值
 * @author: zhang
 * @date: 2022/1/29 20:33
 */
public class Example7 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntegerSource())
                .map(r -> Tuple2.of(r, 1))
                .returns(Types.TUPLE(Types.INT,Types.INT))
                .keyBy(r -> 1)
                .reduce(new ReduceFunction<Tuple2<Integer, Integer>>() {
                    @Override
                    public Tuple2<Integer, Integer> reduce(Tuple2<Integer, Integer> value1, Tuple2<Integer, Integer> value2) throws Exception {

                        return Tuple2.of(
                                value1.f0 + value2.f0 ,
                                value1.f1 + value2.f1
                        );
                    }
                })
                .map(r->r.f0/r.f1)
                .print("avg>>>>");

        env.execute();
    }
}
